package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Netval;
import com.example.mapper.NetvalMapper;
import com.example.redis.dto.FundSearchDto;
import com.example.redis.service.IFundWarmUpService;
import com.example.service.INetvalService;
import com.example.utils.TableDataInfo;
import com.example.vo.FundVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.List;

@Service
public class NetvalServiceImpl extends ServiceImpl<NetvalMapper, Netval> implements INetvalService {

    @Autowired
    private NetvalMapper netvalMapper;
    @Autowired
    private IFundWarmUpService fundWarmUpService;

    @Override
    public TableDataInfo fund(Integer pageNum,Integer pageSize, String sortField,String sortDirection) {

        if (StringUtils.isEmpty(pageNum)){
            pageNum=1;
        }
        if (StringUtils.isEmpty(pageSize)){
            pageSize=4;
        }
        if (StringUtils.isEmpty(sortField)){
            sortField="unit_net_val";
        }
        if (StringUtils.isEmpty(sortDirection)){
            sortDirection="Desc";
        }
        int start = (pageNum-1)*pageSize;


        FundSearchDto dto = fundWarmUpService.getAllFund(sortField,sortDirection);

        //总条数
        List<String> fundList = dto.getFundList();
        String s1 = fundList.get(0);
        System.out.println(s1);
        Integer totalCount = dto.getFundList().size();

        //页数
        Integer pages = totalCount / pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
        List<String> subList =null;
        List<List<String>> allSubList =new ArrayList<>();
        for (int i = 0; i <= pages; i++) {
            Integer fromIndex = i * pageSize;
            //如果总数少于pageSize,为了防止数组越界,toIndex直接使用totalCount即可
            int toIndex = Math.min(totalCount, (i + 1) * pageSize);
            subList = dto.getFundList().subList(fromIndex, toIndex);
            //总数不到一页或者刚好等于一页的时候,只需要处理一次就可以退出for循环了
            if (toIndex == totalCount) {
                break;
            }
            allSubList.add(subList);
        }

        if (start<0){
            start=0;
        }else if (start>totalCount/pageSize+1){
            start=pages;
        }
        System.err.println("allSubList"+allSubList);
        System.err.println("start"+start);
        List<String> strings = allSubList.get(start);

        List<FundVO> voList2 = new ArrayList<>();
        for (String s : strings) {
            for (FundVO vo : dto.getVoList()) {
                if (vo.getFundShortName().equals(s)){
                    voList2.add(vo);
                }
            }
        }

        return new TableDataInfo(totalCount,voList2);
    }
}
